﻿using System;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Xml;

namespace IDesktop.Core {
    public class Weather : IWeatherProvider {
        private string _locationUrl = "http://www.weather.com.cn/data/listinfo/city{0}.xml";
        private string _weatherQueryUrl = "http://www.weather.com.cn/data/cityinfo/{code}.html";
        private string _futureWeatherQueryUrl = "http://m.weather.com.cn/data/{code}.html";
        private Location _location;

        /// <summary>
        /// 城市代码列表
        /// </summary>
        public Location Location {
            get {
                if (_location == null) {
                    GetLocation();
                }
                return _location;
            }
        }

        /// <summary>
        /// 构造Weather实例
        /// </summary>
        /// <param name="locationUrl">获取城市代码的地址</param>
        /// <param name="weatherQueryUrl">查询当天天气的地址</param>
        /// <param name="futureWeatherQueryUrl">查询未来六天天气的地址</param>
        public Weather(string locationUrl, string weatherQueryUrl, string futureWeatherQueryUrl) {
            _locationUrl = locationUrl;
            _weatherQueryUrl = weatherQueryUrl;
            _futureWeatherQueryUrl = futureWeatherQueryUrl;
        }

        public void GetLocation() {
            _location = new Location();
            _location.LocationID = string.Empty;
            GetLocation(_location);
        }

        public WeatherInfo GetWeather(string id, string name) {
            WeatherInfo weatherInfo = new WeatherInfo();
            string url = string.Format(_weatherQueryUrl, id);
            string content = Downloader.Download(url);
            if (!string.IsNullOrEmpty(content)) {
                Regex regex = new Regex(@"\{[^{}]*}");
                Match match = regex.Match(content);
                content = match.Groups[0].ToString().Replace("cityid", "ID").Replace("city", "Name").Replace("weather", "DayWeather").Replace("temp1", "DayTemperature").Replace("temp2", "NightTemperature").Replace("ptime", "UpdateTime");

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                weatherInfo = serializer.Deserialize<WeatherInfo>(content);
            }
            return weatherInfo;
        }


        public FutureWeatherInfo GetFutureWeather(string id, string name) {
            FutureWeatherInfo futureWeatherInfo = new FutureWeatherInfo();
            string url = string.Format(_futureWeatherQueryUrl, id);
            string content = Downloader.Download(url);
            if (!string.IsNullOrEmpty(content)) {
                Regex regex = new Regex(@"\{[^{}]*}");
                Match match = regex.Match(content);
                content = match.Groups[0].ToString();

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                futureWeatherInfo = serializer.Deserialize<FutureWeatherInfo>(content);
            }
            return futureWeatherInfo;
        }

        /// <summary>
        /// 保存城市代码列表
        /// </summary>
        public void Sava() {
            XmlDocument document = new XmlDocument();
            XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "utf-8", null);
            document.AppendChild(declaration);
            XmlElement element = document.CreateElement("Citys");
            element.SetAttribute("ID", _location.LocationID);
            element.SetAttribute("Name", _location.LocationName);
            document.AppendChild(element);
            Save(_location, document, element);
            document.Save("Citys.xml");
        }

        private void GetLocation(Location place) {
            string url = string.Format(_locationUrl, place.LocationID);
            string content = Downloader.Download(url);
            if (!string.IsNullOrEmpty(content)) {
                string[] citys = content.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                Location location;
                foreach (var item in citys) {
                    location = new Location();
                    string[] city = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    location.LocationID = city[0];
                    location.LocationName = city[1];
                    location.Parent = place;
                    place.Children.Add(location);
                    if (!place.LocationID.Equals(location.LocationID)) {
                        GetLocation(location);
                    }
                }
            }
        }

        private void Save(Location place, XmlDocument document, XmlElement element) {
            XmlElement subElement;
            foreach (Location location in place.Children) {
                subElement = document.CreateElement("City");
                subElement.SetAttribute("ID", location.LocationID);
                subElement.SetAttribute("Name", location.LocationName);
                element.AppendChild(subElement);
                if (location.Children.Count > 0) {
                    Save(location, document, subElement);
                }
            }
        }
    }
}
